#include "CSystem.h"
#include "CVector.h"

#include "CMetaClass.h"

CSystem::CSystem():
	_allocated(0),
	_num_allocs(0),
	_num_frees(0),
	_metaclass_registry(NULL),
	_is_inited(false)
{
	std::cout << std::endl << "in CSystem costr" << std::endl;
}

CSystem::~CSystem()
{
	std::cout << std::endl << "in CSystem destr" << std::endl;

	shutdown();
}

bool CSystem::init()
{
	if (_is_inited)
	{
		return true;
	}

	_allocated = 0;
	_num_allocs = 0;
	_num_frees = 0;

	Mem_Init();

	gEnv->p_system = this;

	_metaclass_registry = new CMetaClassRegistry();
	_metaclass_registry->init();

	_is_inited = true;

	return true;
}

bool CSystem::shutdown()
{
	if (!_is_inited)
	{
		return true;
	}

	_metaclass_registry->shutdown();
	delete _metaclass_registry;
	_metaclass_registry = NULL;

	Mem_Shutdown();

	_is_inited = false;

	return true;
}

void * CSystem::sysAlloc(size_t size)
{
	void * p = Mem_Alloc(size);

	if (p)
	{
		_allocated += size;
		++_num_allocs;
	}

	return p;
}

size_t CSystem::sysFree(void * p)
{
	size_t size = Mem_Free(p);

	_allocated -= size;
	++_num_frees;

	return size;
}

void CSystem::sysMemInfo()
{
	memoryStats_t stats;
	Mem_GetStats(stats);

	std::cout << std::endl
				<< "Mem stats:\n  num: " << stats.num 
						<< "\n  min size: " << stats.minSize 
						<< "\n  max size: " << stats.maxSize
						<< "\n  total size: " << stats.totalSize << std::endl;
}

void CSystem::testMem()
{
	std::cout << std::endl << "in test mem" << std::endl;

	void * p = (void *)(new char[16]);

	((char*)p)[0] = 2;

	delete[] p;

	CVec3 vec;

	vec.toYaw();

	std::cout << std::endl << "end test mem" << std::endl;
}

SSystemGlobalEnvironment * CSystem::getSystemGlobalEnvironment()
{
	return gEnv;
}

CMetaClassRegistry * CSystem::getMetaClassRegistry()
{
	return _metaclass_registry;
}